<template>
  <div class="ai-chat-container">
    <div class="chat-header">
      <div class="header-left">
        <h2>AI助手</h2>
        <el-tag type="success" effect="plain">在线</el-tag>
      </div>
      <el-button type="danger" @click="clearChat" :disabled="chatMessages.length === 0">
        清空对话
      </el-button>
    </div>

    <div class="chat-content">
      <div class="chat-messages" ref="chatMessages">
        <div v-for="(message, index) in chatMessages" 
             :key="index" 
             :class="['message-item', message.type]">
          <div class="message-time">{{ formatTime(message.timestamp) }}</div>
          <div class="message-content" :class="{ 'error-message': message.isError }">
            <div class="message-avatar">
              <el-avatar :size="40" :src="message.type === 'user' ? userAvatar : aiAvatar" />
            </div>
            <div class="message-body">
              <div class="message-text">{{ message.content }}</div>
              <div v-if="message.type === 'ai'" class="message-actions">
                <el-button 
                  type="text" 
                  size="small" 
                  @click="copyMessage(message.content)"
                  :icon="CopyDocument"
                >
                  复制
                </el-button>
                <el-button 
                  type="text" 
                  size="small" 
                  @click="regenerateResponse(index)"
                  :icon="Refresh"
                >
                  重新生成
                </el-button>
              </div>
            </div>
          </div>
        </div>
        <div v-if="loading" class="message-item ai">
          <div class="message-content">
            <div class="message-avatar">
              <el-avatar :size="40" :src="aiAvatar" />
            </div>
            <div class="message-body">
              <div class="loading-dots">
                <span></span>
                <span></span>
                <span></span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="chat-input-wrapper">
        <div class="chat-input">
          <el-input
            v-model="userInput"
            type="textarea"
            :rows="3"
            placeholder="请输入您的问题或要求...（Ctrl + Enter 发送）"
            :disabled="loading"
            @keyup.enter.ctrl="sendMessage"
          />
          <div class="input-actions">
            <el-button 
              type="primary" 
              @click="sendMessage" 
              :loading="loading"
              :disabled="!userInput.trim()"
            >
              发送
            </el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { CopyDocument, Refresh } from '@element-plus/icons-vue'
import { sendMessageToAI, getAIChatHistory, clearAIChatHistory } from '@/api/VideoAI'
import dayjs from 'dayjs'

const props = defineProps({
  context: {
    type: Object,
    default: () => ({})
  }
})

const chatMessages = ref([])
const userInput = ref('')
const chatMessagesRef = ref(null)
const loading = ref(false)

// 头像
const userAvatar = 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'
const aiAvatar = 'https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png'

// 格式化时间
const formatTime = (timestamp) => {
  return dayjs(timestamp).format('YYYY-MM-DD HH:mm:ss')
}

// 加载对话历史
const loadChatHistory = async () => {
  try {
    const response = await getAIChatHistory()
    chatMessages.value = response.data
    await scrollToBottom()
  } catch (error) {
    ElMessage.error('加载对话历史失败')
  }
}

// 发送消息
const sendMessage = async () => {
  if (!userInput.value.trim() || loading.value) return
  
  const message = userInput.value.trim()
  userInput.value = ''
  
  // 添加用户消息
  chatMessages.value.push({
    type: 'user',
    content: message,
    timestamp: new Date().toISOString()
  })
  
  // 立即滚动到底部
  await scrollToBottom()
  
  loading.value = true
  
  try {
    const response = await sendMessageToAI({
      message,
      context: props.context
    })
    
    // 添加AI回复
    chatMessages.value.push({
      type: 'ai',
      content: response.data.reply,
      timestamp: new Date().toISOString()
    })
    
    await scrollToBottom()
  } catch (error) {
    // 添加错误提示消息
    chatMessages.value.push({
      type: 'ai',
      content: '抱歉，AI助手暂时无法回应，请稍后再试。',
      timestamp: new Date().toISOString(),
      isError: true
    })
    
    ElMessage.error(error.response?.data?.message || '发送消息失败')
    await scrollToBottom()
  } finally {
    loading.value = false
  }
}

// 重新生成AI回复
const regenerateResponse = async (index) => {
  if (loading.value) return
  
  // 获取该消息之前的对话历史
  const previousMessages = chatMessages.value.slice(0, index + 1)
  const lastUserMessage = previousMessages.findLast(msg => msg.type === 'user')
  
  if (!lastUserMessage) return
  
  loading.value = true
  
  try {
    const response = await sendMessageToAI({
      message: lastUserMessage.content,
      context: props.context,
      regenerate: true
    })
    
    // 更新AI回复
    chatMessages.value[index] = {
      type: 'ai',
      content: response.data.reply,
      timestamp: new Date().toISOString()
    }
    
    await scrollToBottom()
  } catch (error) {
    // 更新为错误提示消息
    chatMessages.value[index] = {
      type: 'ai',
      content: '抱歉，重新生成失败，请稍后再试。',
      timestamp: new Date().toISOString(),
      isError: true
    }
    
    ElMessage.error(error.response?.data?.message || '重新生成回复失败')
    await scrollToBottom()
  } finally {
    loading.value = false
  }
}

// 复制消息内容
const copyMessage = async (content) => {
  try {
    await navigator.clipboard.writeText(content)
    ElMessage.success('复制成功')
  } catch (error) {
    ElMessage.error('复制失败')
  }
}

// 清空对话
const clearChat = async () => {
  try {
    await clearAIChatHistory()
    chatMessages.value = []
    ElMessage.success('对话已清空')
  } catch (error) {
    ElMessage.error('清空对话失败')
  }
}

// 滚动到底部
const scrollToBottom = async () => {
  await nextTick()
  if (chatMessagesRef.value) {
    chatMessagesRef.value.scrollTop = chatMessagesRef.value.scrollHeight
  }
}

onMounted(() => {
  loadChatHistory()
})
</script>

<style scoped>
.ai-chat-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.chat-header {
  padding: 20px;
  border-bottom: 1px solid #ebeef5;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-shrink: 0;
}

.chat-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 20px;
  gap: 20px;
  overflow: hidden;
  min-height: 0;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
  background: #f5f7fa;
  border-radius: 8px;
  min-height: 0;
}

.chat-input-wrapper {
  flex-shrink: 0;
  background: #fff;
  padding: 20px;
  border-top: 1px solid #ebeef5;
  margin: 0 -20px -20px -20px;
}

.chat-input {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.message-item {
  margin-bottom: 20px;
  width: 100%;
}

.message-time {
  text-align: center;
  color: #909399;
  font-size: 12px;
  margin-bottom: 8px;
}

.message-content {
  display: flex;
  gap: 12px;
  max-width: 80%;
  margin: 0 auto;
}

.message-item.user .message-content {
  margin-left: auto;
  flex-direction: row-reverse;
}

.message-body {
  flex: 1;
  background: #fff;
  padding: 12px;
  border-radius: 8px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  word-break: break-word;
}

.message-item.user .message-body {
  background: #1a73e8;
  color: #fff;
}

.message-actions {
  margin-top: 8px;
  display: flex;
  gap: 8px;
  justify-content: flex-end;
}

.loading-dots {
  display: flex;
  gap: 4px;
  padding: 4px 0;
}

.loading-dots span {
  width: 8px;
  height: 8px;
  background: #909399;
  border-radius: 50%;
  animation: bounce 1.4s infinite ease-in-out;
}

.loading-dots span:nth-child(1) { animation-delay: -0.32s; }
.loading-dots span:nth-child(2) { animation-delay: -0.16s; }

@keyframes bounce {
  0%, 80%, 100% { transform: scale(0); }
  40% { transform: scale(1); }
}

.input-actions {
  display: flex;
  justify-content: flex-end;
}

.chat-input .el-input {
  flex: 1;
}

.chat-input .el-input.is-disabled .el-input__wrapper {
  background-color: #f5f7fa;
}

.error-message .message-body {
  background: #fef0f0;
  color: #f56c6c;
}

.message-body:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}
</style> 